﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPop.Pop3;
using System.Threading;
using PInitiatives.Helpers;
using OpenPop.Mime;

namespace PInitiatives.Outlook
{
    public class EmailPopInterface : EmailAccessStrategy
    {
        public override List<String> EmailRetrievingAlgorithm()
        {
            using (Pop3Client client = new Pop3Client())
            {
                //make sure client is connected
                if (!client.Connected)
                {
                    // Connect to the server
                    client.Connect("pop.gmail.com", 995, true);

                    // Authenticate
                    client.Authenticate(SettingsManager.GetSettingValue("Outlook.Email.Address"), SettingsManager.GetSettingValue("Outlook.Email.Password"));
                }
                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                //download all messages
                List<Message> allMessages = new List<Message>(messageCount);

                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }
                List<String> rawTextMessages = new List<String>(messageCount);
                foreach (Message item in allMessages)
                {
                    String textVersion;
                    List<MessagePart> textVersions = item.FindAllTextVersions();
                    if (textVersions.Count >= 1)
                        textVersion = textVersions[0].GetBodyAsText();
                    else
                        textVersion = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";

                    rawTextMessages.Add(textVersion);
                    System.Diagnostics.Debug.Write("Sciagnieto wiaadomosci: " + messageCount + "\n");
                }
                int counter = 0;
                                        
                client.Disconnect();
                    
                return rawTextMessages;
            }
            
        }
    }
}